/**
 * 项目申请控制器
 * 处理项目申请相关的云函数请求
 */

const BaseProjectController = require('./base_project_controller.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const dataUtil = require('../../../framework/helpers/data_util.js');
const util = require('../../../framework/helpers/util.js');
const cloudUtil = require('../../../framework/cloud/cloud_util.js');
const ProjectApplyModel = require('../model/project_apply_model.js');
const ProjectApplyHistoryModel = require('../model/project_apply_history_model.js');

class ProjectApplyController extends BaseProjectController {
    constructor(route, openId, event) {
        super(route, openId, event);
        
        // 项目申请状态
        this.PROJECT_STATUS = {
            PLANNING: 10,       // 规划中
            DESIGN: 20,         // 设计中
            DEVELOPMENT: 30,    // 开发中
            TESTING: 40,        // 测试中
            REVIEW: 50,         // 评审中
            COMPLETED: 60,      // 已完成
            CANCELLED: 99       // 已取消
        };
        
        // 活动状态
        this.ACTIVE_STATUS = {
            // 规划阶段
            PLAN_DRAFT: 11,            // 草稿
            PLAN_REVIEW: 12,           // 评审中
            PLAN_APPROVED: 13,         // 已批准

            // 设计阶段
            DESIGN_DRAFT: 21,          // 草稿
            DESIGN_REVIEW: 22,         // 评审中
            DESIGN_APPROVED: 23,       // 已批准

            // 开发阶段
            DEV_ONGOING: 31,           // 进行中
            DEV_REVIEW: 32,            // 评审中
            DEV_COMPLETED: 33,         // 已完成

            // 测试阶段
            TEST_ONGOING: 41,          // 进行中
            TEST_FAILED: 42,           // 未通过
            TEST_PASSED: 43,           // 已通过

            // 评审阶段
            REVIEW_ONGOING: 51,        // 进行中
            REVIEW_FAILED: 52,         // 未通过
            REVIEW_PASSED: 53,         // 已通过

            // 完成阶段
            COMPLETED: 60              // 已完成
        };
    }
    
    /**
     * 创建项目申请
     */
    async createApply() {
        // 数据校验
        const rules = {
            applicationType: 'must|string|name=方案类型',
            name: 'must|string|min:2|max:50|name=型号',
            customerName: 'must|string|min:2|max:50|name=客户名称',
            startDate: 'must|int|name=开始日期',
            deadline: 'must|int|name=截止日期',
            priority: 'string|name=优先级'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        
        // 添加创建信息
        const timestamp = timeUtil.time();
        input.APPLY_STATUS = this.PROJECT_STATUS.PLANNING;
        input.APPLY_STATUS_NAME = '规划中';
        input.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.PLAN_DRAFT;
        input.APPLY_ACTIVE_STATUS_NAME = '草稿';
        input.APPLY_TIME = timestamp;
        input.APPLY_UPDATE_TIME = timestamp;
        input.APPLICANT_ID = this._userId;
        input.APPLICANT_NAME = await this.getNameByUserID(this._userId);
        
        // 创建申请
        const model = new ProjectApplyModel();
        const id = await model.insert(input);
        
        // 记录申请历史
        await this._addApplyHistory(id, null, {
            APPLY_STATUS: input.APPLY_STATUS,
            APPLY_STATUS_NAME: input.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: input.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: input.APPLY_ACTIVE_STATUS_NAME
        }, 'create', '创建项目申请');
        
        return { id };
    }
    
    /**
     * 更新项目申请
     */
    async updateApply() {
        // 数据校验
        const rules = {
            id: 'must|id|name=申请ID',
            applicationType: 'string|name=方案类型',
            name: 'string|min:2|max:50|name=型号',
            customerName: 'string|min:2|max:50|name=客户名称',
            startDate: 'int|name=开始日期',
            deadline: 'int|name=截止日期',
            priority: 'string|name=优先级'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const id = input.id;
        delete input.id;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: id });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限
        if (oldData.APPLICANT_ID !== this._userId && !this._admin) {
            this.AppError('无权更新此申请');
        }
        
        // 检查状态
        if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.PLANNING || 
            oldData.APPLY_ACTIVE_STATUS !== this.ACTIVE_STATUS.PLAN_DRAFT) {
            this.AppError('只能更新草稿状态的申请');
        }
        
        // 更新申请
        input.APPLY_UPDATE_TIME = timeUtil.time();
        await model.edit({ _id: id }, input);
        
        return { id };
    }
    
    /**
     * 提交项目申请审核
     */
    async submitApply() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const applyId = input.applyId;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: applyId });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限
        if (oldData.APPLICANT_ID !== this._userId && !this._admin) {
            this.AppError('无权提交此申请');
        }
        
        // 检查状态
        if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.PLANNING || 
            oldData.APPLY_ACTIVE_STATUS !== this.ACTIVE_STATUS.PLAN_DRAFT) {
            this.AppError('只能提交草稿状态的申请');
        }
        
        // 更新状态
        const updateData = {
            APPLY_ACTIVE_STATUS: this.ACTIVE_STATUS.PLAN_REVIEW,
            APPLY_ACTIVE_STATUS_NAME: '评审中',
            APPLY_UPDATE_TIME: timeUtil.time()
        };
        
        await model.edit({ _id: applyId }, updateData);
        
        // 记录申请历史
        await this._addApplyHistory(applyId, {
            APPLY_STATUS: oldData.APPLY_STATUS,
            APPLY_STATUS_NAME: oldData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: oldData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: oldData.APPLY_ACTIVE_STATUS_NAME
        }, {
            APPLY_STATUS: oldData.APPLY_STATUS,
            APPLY_STATUS_NAME: oldData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: updateData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: updateData.APPLY_ACTIVE_STATUS_NAME
        }, 'submit_for_approval', '提交申请审核');
        
        return { id: applyId };
    }
    
    /**
     * 审批项目申请
     */
    async approveApply() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID',
            isApprove: 'must|bool|name=是否通过',
            comment: 'string|max:200|name=审批意见'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const { applyId, isApprove, comment } = input;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: applyId });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限 - 只有管理员可以审批
        if (!this._admin) {
            this.AppError('无权审批申请');
        }
        
        // 检查状态 - 只能审批评审中状态
        if (![this.ACTIVE_STATUS.PLAN_REVIEW, this.ACTIVE_STATUS.DESIGN_REVIEW, 
            this.ACTIVE_STATUS.DEV_REVIEW, this.ACTIVE_STATUS.REVIEW_ONGOING].includes(oldData.APPLY_ACTIVE_STATUS)) {
            this.AppError('此申请不在可审批状态');
        }
        
        // 根据不同状态处理审批结果
        let updateData = {
            APPLY_UPDATE_TIME: timeUtil.time()
        };
        
        if (isApprove) {
            // 通过审批
            switch (oldData.APPLY_STATUS) {
                case this.PROJECT_STATUS.PLANNING:
                    // 规划审批通过，进入设计阶段
                    updateData.APPLY_STATUS = this.PROJECT_STATUS.DESIGN;
                    updateData.APPLY_STATUS_NAME = '设计中';
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.DESIGN_DRAFT;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '草稿';
                    break;
                case this.PROJECT_STATUS.DESIGN:
                    // 设计审批通过，进入开发阶段
                    updateData.APPLY_STATUS = this.PROJECT_STATUS.DEVELOPMENT;
                    updateData.APPLY_STATUS_NAME = '开发中';
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.DEV_ONGOING;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '进行中';
                    break;
                case this.PROJECT_STATUS.REVIEW:
                    // 最终评审通过，项目完成
                    updateData.APPLY_STATUS = this.PROJECT_STATUS.COMPLETED;
                    updateData.APPLY_STATUS_NAME = '已完成';
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.COMPLETED;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '已完成';
                    break;
                default:
                    // 其他阶段审批通过，状态保持不变但活动状态变为已批准
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.PLAN_APPROVED;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '已批准';
            }
        } else {
            // 未通过审批，回到草稿状态
            switch (oldData.APPLY_STATUS) {
                case this.PROJECT_STATUS.PLANNING:
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.PLAN_DRAFT;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '草稿';
                    break;
                case this.PROJECT_STATUS.DESIGN:
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.DESIGN_DRAFT;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '草稿';
                    break;
                case this.PROJECT_STATUS.REVIEW:
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.REVIEW_FAILED;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '未通过';
                    break;
                default:
                    updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.PLAN_DRAFT;
                    updateData.APPLY_ACTIVE_STATUS_NAME = '草稿';
            }
        }
        
        // 更新状态
        await model.edit({ _id: applyId }, updateData);
        
        // 记录审批历史
        await this._addApplyHistory(applyId, {
            APPLY_STATUS: oldData.APPLY_STATUS,
            APPLY_STATUS_NAME: oldData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: oldData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: oldData.APPLY_ACTIVE_STATUS_NAME
        }, {
            APPLY_STATUS: updateData.APPLY_STATUS || oldData.APPLY_STATUS,
            APPLY_STATUS_NAME: updateData.APPLY_STATUS_NAME || oldData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: updateData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: updateData.APPLY_ACTIVE_STATUS_NAME
        }, isApprove ? 'approve' : 'reject', isApprove ? '审批通过' : '审批拒绝', comment);
        
        return { id: applyId };
    }
    
    /**
     * 取消项目申请
     */
    async cancelApply() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID',
            reason: 'string|max:200|name=取消原因'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const { applyId, reason } = input;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: applyId });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限
        if (oldData.APPLICANT_ID !== this._userId && !this._admin) {
            this.AppError('无权取消此申请');
        }
        
        // 检查状态 - 已完成或已取消的项目不能取消
        if ([this.PROJECT_STATUS.COMPLETED, this.PROJECT_STATUS.CANCELLED].includes(oldData.APPLY_STATUS)) {
            this.AppError('此申请不能取消');
        }
        
        // 更新状态
        const updateData = {
            APPLY_STATUS: this.PROJECT_STATUS.CANCELLED,
            APPLY_STATUS_NAME: '已取消',
            APPLY_ACTIVE_STATUS: 0,
            APPLY_ACTIVE_STATUS_NAME: '已取消',
            APPLY_UPDATE_TIME: timeUtil.time(),
            CANCEL_REASON: reason || '申请人取消'
        };
        
        await model.edit({ _id: applyId }, updateData);
        
        // 记录取消历史
        await this._addApplyHistory(applyId, {
            APPLY_STATUS: oldData.APPLY_STATUS,
            APPLY_STATUS_NAME: oldData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: oldData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: oldData.APPLY_ACTIVE_STATUS_NAME
        }, {
            APPLY_STATUS: updateData.APPLY_STATUS,
            APPLY_STATUS_NAME: updateData.APPLY_STATUS_NAME,
            APPLY_ACTIVE_STATUS: updateData.APPLY_ACTIVE_STATUS,
            APPLY_ACTIVE_STATUS_NAME: updateData.APPLY_ACTIVE_STATUS_NAME
        }, 'cancel', '取消申请', reason);
        
        return { id: applyId };
    }
    
    /**
     * 获取项目申请详情
     */
    async getApplyDetail() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const applyId = input.applyId;
        
        // 查询数据
        const model = new ProjectApplyModel();
        const data = await model.getOne({ _id: applyId });
        if (!data) {
            this.AppError('项目申请不存在');
        }
        
        return { data };
    }
    
    /**
     * 获取项目申请列表
     */
    async getApplyList() {
        // 数据校验
        const rules = {
            search: 'string|min:1|max:30|name=搜索条件',
            sortType: 'string|name=排序类型',
            sortOrder: 'string|name=排序方向',
            status: 'int|name=状态筛选',
            page: 'must|int|default=1|name=当前页码',
            size: 'must|int|default=10|name=每页记录数'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const { search, sortType, sortOrder, status, page, size } = input;
        
        // 构建查询条件
        const where = {};
        
        // 搜索
        if (search) {
            const searchRegex = new RegExp(search, 'i');
            where['$or'] = [
                { model: searchRegex },
                { customerName: searchRegex },
                { applicationType: searchRegex },
                { PROJECT_TITLE: searchRegex },
                { PROJECT_CUSTOMER_NAME: searchRegex }
            ];
        }
        
        // 状态筛选
        if (status > 0) {
            where.APPLY_STATUS = status;
        }
        
        // 非管理员只能查看自己的申请
        if (!this._admin) {
            where.APPLICANT_ID = this._userId;
        }
        
        // 构建排序
        const orderBy = {};
        if (sortType === 'time') {
            orderBy.APPLY_UPDATE_TIME = sortOrder === 'asc' ? 1 : -1;
        } else if (sortType === 'status') {
            orderBy.APPLY_STATUS = sortOrder === 'asc' ? 1 : -1;
            orderBy.APPLY_ACTIVE_STATUS = sortOrder === 'asc' ? 1 : -1;
        } else {
            // 默认按更新时间倒序
            orderBy.APPLY_UPDATE_TIME = -1;
        }
        
        // 查询数据
        const model = new ProjectApplyModel();
        const result = await model.getList(where, page, size, orderBy);
        
        return result;
    }
    
    /**
     * 获取项目申请历史记录
     */
    async getApplyHistory() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const applyId = input.applyId;
        
        // 查询申请是否存在
        const model = new ProjectApplyModel();
        const apply = await model.getOne({ _id: applyId });
        if (!apply) {
            this.AppError('项目申请不存在');
        }
        
        // 查询历史记录
        const historyModel = new ProjectApplyHistoryModel();
        const data = await historyModel.getList({ APPLY_ID: applyId }, 1, 100, { CREATE_TIME: 1 });
        
        return { data: data.list };
    }
    
    /**
     * 触发项目状态流转事件
     */
    async triggerEvent() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID',
            eventCode: 'must|string|name=事件代码',
            eventData: 'object|name=事件数据'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const { applyId, eventCode, eventData } = input;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: applyId });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限
        if (oldData.APPLICANT_ID !== this._userId && !this._admin) {
            this.AppError('无权操作此申请');
        }
        
        // 获取当前用户名
        const userName = await this.getNameByUserID(this._userId);
        
        // 根据事件代码处理状态流转
        let updateData = {
            APPLY_UPDATE_TIME: timeUtil.time()
        };
        
        let eventResult = null;
        
        switch (eventCode) {
            case 'complete_design':
                // 完成设计 -> 开发阶段
                if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.DESIGN) {
                    this.AppError('当前状态不能执行此操作');
                }
                
                updateData.APPLY_STATUS = this.PROJECT_STATUS.DEVELOPMENT;
                updateData.APPLY_STATUS_NAME = '开发中';
                updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.DEV_ONGOING;
                updateData.APPLY_ACTIVE_STATUS_NAME = '进行中';
                eventResult = { event: '完成设计', comment: eventData.comment || '设计阶段完成' };
                break;
                
            case 'complete_development':
                // 完成开发 -> 测试阶段
                if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.DEVELOPMENT) {
                    this.AppError('当前状态不能执行此操作');
                }
                
                updateData.APPLY_STATUS = this.PROJECT_STATUS.TESTING;
                updateData.APPLY_STATUS_NAME = '测试中';
                updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.TEST_ONGOING;
                updateData.APPLY_ACTIVE_STATUS_NAME = '进行中';
                eventResult = { event: '完成开发', comment: eventData.comment || '开发阶段完成' };
                break;
                
            case 'complete_testing':
                // 完成测试 -> 评审阶段
                if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.TESTING) {
                    this.AppError('当前状态不能执行此操作');
                }
                
                updateData.APPLY_STATUS = this.PROJECT_STATUS.REVIEW;
                updateData.APPLY_STATUS_NAME = '评审中';
                updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.REVIEW_ONGOING;
                updateData.APPLY_ACTIVE_STATUS_NAME = '进行中';
                eventResult = { event: '完成测试', comment: eventData.comment || '测试阶段完成' };
                break;
                
            case 'sleep_request':
                // 休眠申请
                if (![this.PROJECT_STATUS.DEVELOPMENT, this.PROJECT_STATUS.TESTING].includes(oldData.APPLY_STATUS)) {
                    this.AppError('当前状态不能申请休眠');
                }
                
                updateData.IS_SLEEP = 1;
                updateData.SLEEP_REASON = eventData.reason || '';
                updateData.SLEEP_TIME = timeUtil.time();
                eventResult = { event: '休眠申请', comment: eventData.reason || '申请休眠' };
                break;
                
            case 'wakeup_request':
                // 唤醒申请
                if (!oldData.IS_SLEEP) {
                    this.AppError('当前项目不是休眠状态');
                }
                
                updateData.IS_SLEEP = 0;
                updateData.WAKEUP_REASON = eventData.reason || '';
                updateData.WAKEUP_TIME = timeUtil.time();
                eventResult = { event: '唤醒申请', comment: eventData.reason || '申请唤醒' };
                break;
                
            case 'complete_project':
                // 完成项目
                if (oldData.APPLY_STATUS !== this.PROJECT_STATUS.REVIEW || 
                    oldData.APPLY_ACTIVE_STATUS !== this.ACTIVE_STATUS.REVIEW_PASSED) {
                    this.AppError('当前状态不能完成项目');
                }
                
                updateData.APPLY_STATUS = this.PROJECT_STATUS.COMPLETED;
                updateData.APPLY_STATUS_NAME = '已完成';
                updateData.APPLY_ACTIVE_STATUS = this.ACTIVE_STATUS.COMPLETED;
                updateData.APPLY_ACTIVE_STATUS_NAME = '已完成';
                updateData.COMPLETE_TIME = timeUtil.time();
                eventResult = { event: '完成项目', comment: eventData.comment || '项目完成' };
                break;
                
            default:
                this.AppError('不支持的事件代码');
        }
        
        // 更新状态
        await model.edit({ _id: applyId }, updateData);
        
        // 记录历史
        if (eventResult) {
            await this._addApplyHistory(applyId, {
                APPLY_STATUS: oldData.APPLY_STATUS,
                APPLY_STATUS_NAME: oldData.APPLY_STATUS_NAME,
                APPLY_ACTIVE_STATUS: oldData.APPLY_ACTIVE_STATUS,
                APPLY_ACTIVE_STATUS_NAME: oldData.APPLY_ACTIVE_STATUS_NAME
            }, {
                APPLY_STATUS: updateData.APPLY_STATUS || oldData.APPLY_STATUS,
                APPLY_STATUS_NAME: updateData.APPLY_STATUS_NAME || oldData.APPLY_STATUS_NAME,
                APPLY_ACTIVE_STATUS: updateData.APPLY_ACTIVE_STATUS || oldData.APPLY_ACTIVE_STATUS,
                APPLY_ACTIVE_STATUS_NAME: updateData.APPLY_ACTIVE_STATUS_NAME || oldData.APPLY_ACTIVE_STATUS_NAME
            }, eventCode, eventResult.event, eventResult.comment);
        }
        
        return { id: applyId };
    }
    
    /**
     * 更新项目申请文件
     */
    async updateApplyFile() {
        // 数据校验
        const rules = {
            applyId: 'must|id|name=申请ID',
            fileType: 'must|string|name=文件类型',
            fileInfo: 'must|object|name=文件信息'
        };
        
        // 获取参数
        const input = this.validateData(rules);
        const { applyId, fileType, fileInfo } = input;
        
        // 查询原始数据
        const model = new ProjectApplyModel();
        const oldData = await model.getOne({ _id: applyId });
        if (!oldData) {
            this.AppError('项目申请不存在');
        }
        
        // 检查权限
        if (oldData.APPLICANT_ID !== this._userId && !this._admin) {
            this.AppError('无权操作此申请');
        }
        
        // 更新文件信息
        const fileField = `files.${fileType}`;
        const updateData = {};
        updateData[fileField] = fileInfo;
        
        await model.edit({ _id: applyId }, updateData);
        
        return { id: applyId };
    }
    
    /**
     * 添加申请历史记录
     * @param {String} applyId 申请ID
     * @param {Object} fromStatus 原状态
     * @param {Object} toStatus 新状态
     * @param {String} eventCode 事件代码
     * @param {String} eventName 事件名称
     * @param {String} comment 备注
     * @returns {Promise}
     */
    async _addApplyHistory(applyId, fromStatus, toStatus, eventCode, eventName, comment = '') {
        const model = new ProjectApplyHistoryModel();
        
        const historyData = {
            APPLY_ID: applyId,
            EVENT_CODE: eventCode,
            EVENT_NAME: eventName,
            FROM_STATUS: fromStatus ? fromStatus.APPLY_STATUS : null,
            FROM_STATUS_NAME: fromStatus ? fromStatus.APPLY_STATUS_NAME : null,
            FROM_ACTIVE_STATUS: fromStatus ? fromStatus.APPLY_ACTIVE_STATUS : null,
            FROM_ACTIVE_STATUS_NAME: fromStatus ? fromStatus.APPLY_ACTIVE_STATUS_NAME : null,
            TO_STATUS: toStatus.APPLY_STATUS,
            TO_STATUS_NAME: toStatus.APPLY_STATUS_NAME,
            TO_ACTIVE_STATUS: toStatus.APPLY_ACTIVE_STATUS,
            TO_ACTIVE_STATUS_NAME: toStatus.APPLY_ACTIVE_STATUS_NAME,
            OPERATOR_ID: this._userId,
            OPERATOR_NAME: await this.getNameByUserID(this._userId),
            COMMENT: comment,
            CREATE_TIME: timeUtil.time()
        };
        
        return await model.insert(historyData);
    }
    
    /**
     * 获取用户名
     * @param {String} userId 用户ID
     * @returns {Promise<String>} 用户名
     */
    async getNameByUserID(userId) {
        if (!userId) return '未知用户';
        
        try {
            const user = await this.getUserByKey(userId);
            return user ? user.USER_NAME : '未知用户';
        } catch (e) {
            return '未知用户';
        }
    }
}

module.exports = ProjectApplyController; 